﻿using System.Web.Mvc;
using Dexter.Logger.Contracts;
using Dexter.Search;
using Dexter.Services;
using Dexter.Web.Mvc.Filters;
using Dexter.Web.Mvc.Results;
using Dexter.Web.Mvc.ViewModel.FrontEnd.CategoryController;
using Dexter.Web.Syndication.Contracts;
using Dexter.Web.Utils;

namespace Dexter.Web.Mvc.Controllers.FrontEnd {
	[DexterCallFilter ( true )]
	public class CategoryController : PublicControllerBase {
		readonly IRssService rssService;

		public CategoryController ( ISearchService searchService , ICommentService commentService , IReferrerService referrerService , IConfigurationService configurationService , IWebUtils webUtils , ILogger logger , IUrlBuilder urlBuilder , IBlogRollService blogRollService , ICategoryService categoryService , IPostService postService , IThemeManager themeManager , ITagService tagService , IPageService pageService , IRssService rssService ) : base ( searchService , commentService , referrerService , configurationService , webUtils , logger , urlBuilder , blogRollService , categoryService , postService , themeManager , tagService , pageService ) {
			this.rssService = rssService;
		}

		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
		public ActionResult Index () {
			var data = base.GetViewData(new CategoryIndexViewData(base.WebUtils, base.Configuration, base.UrlBuilder));
			data.Posts = PostService.GetCompleteListOfPostDtos(0, 10000000);

			return View(data);
		}

		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
		public ActionResult Archive ( string id , int? page ) {
			if ( string.IsNullOrEmpty ( id ) ) {
				return HttpNotFound ( );
			}

			int pageIndex = page ?? 1;

			pageIndex--;

			string categoryName = HttpContext.Server.UrlDecode ( id ).ToLowerInvariant ( );


			var data = base.GetViewData ( new CategoryArchiveViewData ( base.WebUtils , base.Configuration , base.UrlBuilder ) );
			data.FilterCategory = CategoryService.GetCategoryDtoByNameWithChilds(categoryName);

			if ( data.FilterCategory == null ) {
				return HttpNotFound ( );
			}

			data.Posts = PostService.GetPostsDtoByCategory(data.FilterCategory, pageIndex, base.Configuration.ElementInListsConfiguration.NumberOfElementsInList);

			return View ( data );
		}

		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
		public ActionResult Rss ( string id ) {
			if ( string.IsNullOrEmpty ( id ) ) {
				return HttpNotFound ( );
			}

			var category = CategoryService.GetCategoryByNameWithChilds ( id );
			var postInCategory = PostService.GetPostsByCategory ( category, 0, base.Configuration.ElementInListsConfiguration.NumberOfElementsInFeed );

			return new RssResult ( base.Configuration , postInCategory.Result , this.rssService , base.UrlBuilder );
		}
	}
}
